﻿using System;
using System.Collections;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web.SessionState;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.IO;

public class ExportarReporte
{
    
	public ExportarReporte()
	{
        
	}
    //<summary>
    //metodo que Exporta un GridView a un Archivo *.csv
    //Parametros GridView que se desea exportar,nombre que tendra el archivo, 
    //pagina en la cual se llama el metodo
    //</summary>
    
    public void ExportarCsv(GridView grdGridView, string nombre,Page pagina)
    {

        pagina.Response.Clear();

        pagina.Response.AddHeader("content-disposition",
        string.Format("attachment;filename={0}.csv", nombre));

        pagina.Response.Charset = "";
        pagina.Response.ContentType = "application/vnd.csv";

        System.IO.StringWriter sWriter;
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        sWriter = new System.IO.StringWriter(sb);
        string Str;

        if (grdGridView.Caption != "")
        {
            sWriter.Write(grdGridView.Caption);
            sWriter.WriteLine(",");
        }
        for (int k = 0; k <= (grdGridView.Columns.Count - 1); k++)
        {
            if (grdGridView.HeaderRow.Cells[k].Text == "&nbsp;")
            {
                sWriter.Write("" + ",");
            }
            else
            {
                sWriter.Write(grdGridView.HeaderRow.Cells[k].Text + ",");
            }
        }

        sWriter.WriteLine(",");


        for (int i = 0; i <= (grdGridView.Rows.Count - 1); i++)
        {

            for (int j = 0; j <= (grdGridView.Columns.Count - 1); j++)
            {

                Str = (grdGridView.Rows[i].Cells[j].Text.ToString());

                if (Str == "&nbsp;")
                    Str = "";

                Str = (Str + ",");
                sWriter.Write(Str);

            }

            sWriter.WriteLine();

        }
        GridViewRow finalgridview = grdGridView.FooterRow;

        for (int k = 0; k <= (grdGridView.Columns.Count - 1); k++)
        {
            Str = (finalgridview.Cells[k].Text.ToString());
            if (Str == "&nbsp;")
            {
                Str = "";
            }
            Str = (Str + ",");
            sWriter.Write(Str);
        }
        sWriter.WriteLine();

        sWriter.Close();
        pagina.Response.Write(sb.ToString());
        pagina.Response.End();

    }
}
